package com.zeei.ems.base.util;

import com.zeei.ems.base.constant.GlobalConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueInformation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * MQ工具类
 */
@Component
public class MQPublishUtil {

    static AmqpTemplate amqpTemplate;
    static AmqpAdmin amqpAdmin;

    @Autowired
    public MQPublishUtil(AmqpTemplate amqpTemplate, AmqpAdmin amqpAdmin) {
        MQPublishUtil.amqpTemplate = amqpTemplate;
        MQPublishUtil.amqpAdmin = amqpAdmin;
    }

    /**
     * 设备反控命令
     *
     * @param msg 消息
     */
    public static void equipCmd(String msg) {
        sendQueueMsg(GlobalConstant.CMD_QUEUE, msg);
    }

    /**
     * 发送消息到指定的队列
     *
     * @param queueName 队列名称
     * @param msg       消息
     */
    public static void sendQueueMsg(String queueName, String msg) {
        if (StringUtils.isNoneBlank(queueName,msg)){
            isExist(queueName);
            amqpTemplate.convertAndSend(queueName, msg);
        }
    }

    /**
     * 判断队列是否存在，如果不存在，先创建队列
     * @param queueName 队列名
     */
    private static void isExist(String queueName) {
        // 获取指定名称队列是否存在
        QueueInformation queueInfo = amqpAdmin.getQueueInfo(queueName);
        if (queueInfo == null) {
            Queue queue = new Queue(queueName,true);
            amqpAdmin.declareQueue(queue);
        }
    }
}
